<?
include_once "DB.php";

session_start();

function verifyPass($user, $pass) {
	// TODO: hash the passwords
	$result = query_db("SELECT ID FROM User WHERE UserName='$user' AND PasswordHash='$pass'");
	if (mysql_num_rows($result) == 1) 
	{
		$row = mysql_fetch_array($result, MYSQL_ASSOC);
		mysql_free_result($result);
		return $row["ID"];
	}
	// if we get 0 or more than 1 user, it's invalid
	return 0;
}

function login($user, $pass) {
	$userid = verifyPass($user, $pass);
	if ($userid > 0) {
		// login script
		$_SESSION['userid'] = $userid;
		return $_SESSION['userid'];
	}
	return -1;
}

function logout() {
	if (isset($_SESSION['userid'])) {
		unset($_SESSION['userid']);
	}
}

function requireLogin() {
	if (isset($_SESSION['userid'])) {
		return $_SESSION['userid'];
	} else {
		if (isset($_POST['txtUserName'])) {
			$uid = login($_POST['txtUserName'], $_POST['txtPassword']);
			if ($uid == -1) {
				echo "<p>login failed | <a href='index.php'>log in page</a></p>";
				die();
			}
		} else {
			echo "<p>not logged in | <a href='index.php'>log in page</a></p>";
			die();
		}
	}
	return -1;
}

function store($name, $value) {
	$_SESSION[$name] = $value;
}

function load($name) {
	if (isset($_SESSION[$name])) {
		return $_SESSION[$name];
	}
	return null;
}

?>
